package com.moto.controller.user;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.moto.Vo.BolgFindAllVO;
import com.moto.Vo.userListBolg;
import com.moto.entity.*;
import com.moto.entityDto.FavoriteDto;
import com.moto.interceptor.BaseContext;
import com.moto.interceptor.JwtProperties;
import com.moto.mapper.BolgMapper;
import com.moto.mapper.FavoriteMapper;
import com.moto.result.Result;
import com.moto.service.*;
import com.moto.utils.PageResult;
import com.moto.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyz
 * @since 2023-08-29
 */
@RestController
@RequestMapping("/moto/bolg")
@Slf4j
@CrossOrigin("*")
@Api(tags = "博客相关接口")
public class BolgController {

    @Autowired
    private IBolgService iBolgService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IBolgsortService bolgsortService;
    @Autowired
    private IFavoriteService favoriteService;
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IHistoryBlogService historyBlogService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/hot")
    @ApiOperation(value = "根据浏览量查询热门文章")
    public Result<List<BolgFindAllVO>> findHotBolg(){
        log.info("根据浏览量查询热门文章");
        List<BolgFindAllVO> list = iBolgService.findHotBolg();
        return Result.success(list);
    }
    @GetMapping
    @Cacheable(cacheNames = "bolg",key = "1")//bolg::1
    @ApiOperation("根据发布时间查询文章")
    public Result<List<BolgFindAllVO>> findAllBolg(){
        log.info("根据浏览量查询热门文章");
//        List<BolgFindAllVO> list=new ArrayList<>();
//        String bolg = stringRedisTemplate.opsForValue().get("bolg");
////        List<BolgFindAllVO> list = (List<BolgFindAllVO>) JSONArray.parse(bolg);
//
//        List<BolgFindAllVO> list = JSON.parseArray(bolg, BolgFindAllVO.class);
//        if (list != null && list.size() > 0) {
//            log.info("从redis中取出list");
//            //如果存在，直接返回，无需查找数据库
//            return Result.success(list);
//        }
        List<BolgFindAllVO> list = iBolgService.findAllBolg();
//        String string = JSON.toJSONString(list);
//        stringRedisTemplate.opsForValue().set("bolg", string);


        return Result.success(list);
    }

    @GetMapping("/article/{bolgId}")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation(value = "文章详情")
    public Result<userListBolg> bolgArticle(@PathVariable int bolgId){
        log.info("文章详情");

        //用户id
        int uId = Math.toIntExact(BaseContext.getCurrentId());

        //查询点击的文章
        LambdaQueryWrapper<Bolg> lqw = new LambdaQueryWrapper<Bolg>();
        lqw.eq(Bolg::getBolgId,bolgId);
        Bolg one = iBolgService.getOne(lqw);
        userListBolg<Bolg> userListBolg = new userListBolg<>();
        userListBolg.setBolg(one);
        //获取作者id
        Integer authorId = one.getUId();

        //查询是否收藏
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id", uId);
        wrapper.eq("bolg_id", bolgId);
        int i = Math.toIntExact(favoriteMapper.selectCount(wrapper));
        userListBolg.setFavorite(i);

        //根据作者id查询作者的头像姓名
        LambdaQueryWrapper<User> lqw1 = new LambdaQueryWrapper<User>();
        lqw1.eq(User::getId,authorId);
        lqw1.select(User::getUsername, User::getPhoto);
        User user = userService.getOne(lqw1);
        userListBolg.setUser(user);

        //给浏览记录表增加记录
        HistoryBlog historyBlog = new HistoryBlog();
        historyBlog.setUId(uId);
        historyBlog.setBolgId(bolgId);
        historyBlog.setUpdateTime(LocalDateTime.now());
        historyBlog.setIsDelete(1);
        historyBlogService.save(historyBlog);
        return Result.success(userListBolg);
    }

    @PostMapping("/publish")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation(value = "发布文章")
    public Result publish(@RequestBody Bolg bolg){
        log.info("发布文章");
        int id = Math.toIntExact(BaseContext.getCurrentId());
        bolg.setUId(id);
        bolg.setPubTime(LocalDateTime.now());
        iBolgService.publish(bolg);
            return Result.success("发布文章成功");
    }

    @PutMapping("/incrementViews/{bolgId}")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation(value = "增加浏览量")
    public Result<String> incrementViews(@PathVariable Integer bolgId){
        log.info("增加浏览量");
        iBolgService.incrementViews(bolgId);
        return Result.success("增加成功");
    }
    @GetMapping("/detail")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation(value = "文章分类")
    public Result<List<Bolgsort>> sortBolg(){
        log.info("文章分类");
        List<Bolgsort> list= bolgsortService.list();
        return Result.success(list);
    }

    @PostMapping("/likess/{bolgId}")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation(value = "点赞")
    public Result<String> like(@PathVariable Integer bolgId){
        log.info("点赞");
        iBolgService.like(bolgId);
        return Result.success("点赞成功");
    }

    /**
     * 根据分类查找博客
     * @param id
     * @return
     */
    @GetMapping("findByIdBolg")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation("根据分类查找博客")
    public Result<List<BolgFindAllVO>> findByIdBolg(Integer id){
        List<BolgFindAllVO> list = iBolgService.findByIdBolg(id);
        return Result.success(list);
    }

    /**
     * 我的发布
     * @param
     * @return
     */
    @GetMapping("findMyBolg")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation("查找我发布的文章")
    public Result<List<Bolg>> findMyBolg(){
        int id = Math.toIntExact(BaseContext.getCurrentId());
        LambdaQueryWrapper<Bolg> lqw = new LambdaQueryWrapper<Bolg>();
        lqw.eq(Bolg::getUId,id);
        List<Bolg> list = iBolgService.list(lqw);
        return Result.success(list);
    }

    @PostMapping("/collect")
    @CacheEvict(cacheNames = "bolg",allEntries = true)
    @ApiOperation(value = "收藏")
    public Result<String> collect(@RequestBody FavoriteDto favoriteDto){
        log.info("收藏：{}",favoriteDto);
        //博客id
        int bolgId = favoriteDto.getBolgId();
        //用户id
        int uId = Math.toIntExact(BaseContext.getCurrentId());

        if (favoriteDto.getBolgState()==1){
            Favorite favorite = new Favorite();
            favorite.setUId(uId);
            favorite.setBolgId(bolgId);
            //判断数用户有没有收藏该帖子
            QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
            wrapper.eq("u_id", uId);
            wrapper.eq("bolg_id", bolgId);
            Long i = favoriteMapper.selectCount(wrapper);
            System.out.println("搜索到数据库中的数据为：" + i);
            if (i > 0) {
                return Result.error("您已收藏该帖子");
            }
            //给收藏表添加数据
            favoriteService.addFavorite(favorite);
            //修改表中收藏量
            iBolgService.collect(bolgId);
            return Result.success("收藏成功");
        }
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_id",uId);
        queryWrapper.eq("bolg_id",favoriteDto.getBolgId());
        favoriteMapper.delete(queryWrapper);
        //修改
        UpdateWrapper<Bolg> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("bolg_id",favoriteDto.getBolgId());
        updateWrapper.setSql("collect = collect-1");
        iBolgService.update(updateWrapper);

        return Result.success("取消收藏");
    }


}
